//
//  CAR_CarDetailViewController.m
//  CarUser
//
//  Created by ayi on 2019/1/7.
//  Copyright © 2019 王森林. All rights reserved.
//

#import "Car_CarDetailViewController.h"

#import "CarDetailViewModel.h"

#import "Car_ContrastCarViewController.h"
#import "HomeBookViewController.h"
#import "Car_ContrastCalculatorViewController.h"

#import "CustomIMSendMessageView.h"
#import <IQKeyboardManager/IQKeyboardManager.h>

@interface Car_CarDetailViewController ()<UIScrollViewDelegate,TabviewViewModelDelegate>

@property (nonatomic, strong) CarDetailViewModel *viewmodel;
@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) UIButton *collectBtn;//收藏
@property (nonatomic, strong) UIButton *shareBtn;//分享
@property (nonatomic, strong) UIButton *contrastBtn;//对比

@property (nonatomic, strong) UIView *bottomView;//更多按钮
@property (nonatomic, strong) UIButton *customerServiceBtn;//客服
@property (nonatomic, strong) UIButton *calculatorBtn;//计算器
@property (nonatomic, strong) UIButton *addToContrastBtn;//加入对比
@property (nonatomic, strong) UIButton *reserveBtn;//预定
@property (nonatomic, strong) UIView *circleview;

@property (nonatomic, strong) CustomIMSendMessageView *sendView;
@property (nonatomic, assign) NSInteger isCollect;//1为收藏，2为未收藏

@end

@implementation Car_CarDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(freshContrastCircle) name:@"Car_CarDetailViewControllerFreshContrast" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateVaule) name:NotificationCenterName_Fresh_Userinfo object:nil];
    [[[IQKeyboardManager sharedManager] disabledDistanceHandlingClasses] addObject:[self class]];
    [[[IQKeyboardManager sharedManager] disabledToolbarClasses] addObject:[self class]];
    
    _viewmodel = [[CarDetailViewModel alloc]init];
    _viewmodel.childtab = self.tableview;
    _viewmodel.childvc = self;
    _viewmodel.SALECAR_ID =  self.SERIES_ID;
    _viewmodel.delegate = self;
    
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(- NAV_HEIGHT, 0, 0, 0));
    }];
    self.tableview.contentInset = UIEdgeInsetsMake(0, 0, TABBAR_HEIGHT + 20, 0);
    
    
    //导航
    _collectBtn = ({
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:IMG(@"ic_car_detail_farorite") forState:UIControlStateNormal];
//        [btn setImage:IMG(@"ic_car_detail_farorite") forState:UIControlStateHighlighted];
        btn.frame = CGRectMake(0, 0, 30, 35);
        btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [btn addTarget:self action:@selector(collectAction) forControlEvents:UIControlEventTouchUpInside];
        [btn setExclusiveTouch:YES];
        btn;
    });
    
//    _shareBtn = ({
//        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [btn setImage:IMG(@"ic_car_detail_share") forState:UIControlStateNormal];
//        btn.frame = CGRectMake(30, 0, 30, 35);
//        [btn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
//        [btn setExclusiveTouch:YES];
//        btn;
//    });
    
    _circleview = [[UIView alloc]init];_circleview.backgroundColor = UIColor.redColor;
    _circleview.layer.masksToBounds = YES;
    _circleview.layer.cornerRadius = 3;
    _circleview.hidden = YES;
    _contrastBtn = ({
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:IMG(@"ic_car_detail_compare") forState:UIControlStateNormal];
        [btn setImage:IMG(@"ic_car_detail_compare") forState:UIControlStateHighlighted];
        btn.frame = CGRectMake(35, 0, 30, 35);
        [btn addTarget:self action:@selector(pushtoContrasAction) forControlEvents:UIControlEventTouchUpInside];
        [btn setExclusiveTouch:YES];
        
        [btn addSubview:_circleview];
        _circleview.frame = CGRectMake(18, 2, 6, 6);
        
        btn;
    });
    
    UIView *btnView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 60, 35)];
    [btnView addSubview:_collectBtn];
    [btnView addSubview:_shareBtn];
    [btnView addSubview:_contrastBtn];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btnView];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    //底部按钮
    _bottomView = [[UIView alloc]init];
    _bottomView.backgroundColor = UIColor.blackColor;
    [self.view addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        (void)make.left.and.bottom.and.right;
        make.height.mas_equalTo(TABBAR_HEIGHT);
    }];
    
    _customerServiceBtn = ({
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = Common_NavigroundColor;
        [btn setImage:IMG(@"ic_car_detail_service") forState:UIControlStateNormal];
        btn.titleLabel.font = FONT_SIZE(14);
        [btn setTitleColor:RGB(195, 195, 195) forState:UIControlStateNormal];
        btn.frame = CGRectMake(0, 0, BOUNDWIDTH/5, 49);
        [btn setTitle:@"客服" forState:UIControlStateNormal];
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
        [btn addTarget:self action:@selector(action1) forControlEvents:UIControlEventTouchUpInside];
        [btn setExclusiveTouch:YES];
        btn;
    });
    
 
    _calculatorBtn = ({
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = Common_NavigroundColor;
        [btn setImage:IMG(@"ic_car_detail_calculator") forState:UIControlStateNormal];
        btn.titleLabel.font = FONT_SIZE(14);
        [btn setTitleColor:RGB(195, 195, 195) forState:UIControlStateNormal];
        btn.frame = CGRectMake(BOUNDWIDTH/5, 0, BOUNDWIDTH/5, 49);
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
        [btn setTitle:@"计算器" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(action2) forControlEvents:UIControlEventTouchUpInside];
        [btn setExclusiveTouch:YES];
        btn;
    });
    _addToContrastBtn = ({
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = UIColor.blackColor;
        btn.titleLabel.font = FONT_SIZE(14);
        [btn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        btn.frame = CGRectMake(BOUNDWIDTH/5 * 2, 0, BOUNDWIDTH * 3/10, 49);
        [btn setTitle:@"加入对比" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(action3) forControlEvents:UIControlEventTouchUpInside];
        [btn setExclusiveTouch:YES];
        btn;
    });
    _reserveBtn = ({
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = Common_BG_yellow;
        btn.frame = CGRectMake(BOUNDWIDTH/5 * 2 + BOUNDWIDTH * 3/10, 0, BOUNDWIDTH * 3/10, 49);
        btn.titleLabel.font = FONT_SIZE(14);
        [btn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        [btn setTitle:@"发车" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(action4) forControlEvents:UIControlEventTouchUpInside];
        [btn setExclusiveTouch:YES];
        btn;
    });
    
 
    
    
    [_bottomView addSubview:_customerServiceBtn];
    [_bottomView addSubview:_calculatorBtn];
    [_bottomView addSubview:_addToContrastBtn];
    [_bottomView addSubview:_reserveBtn];
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(BOUNDWIDTH/5, 0, 0.5, 49)];
    lineLabel.backgroundColor = [UIColor whiteColor];
    [_bottomView addSubview:lineLabel];
    
    self.bottomView.hidden = YES;
    self.navigationItem.rightBarButtonItem.customView.hidden = YES;
    
    @weakify(self);
    self.sendView = [[CustomIMSendMessageView alloc]initOnlySendWithFrame:CGRectMake(0, BOUNDHEIGHT, BOUNDWIDTH, 50)];
    [self.sendView setCustomIMCallBack:^(UITextField * _Nonnull textf) {
        @strongify(self);
        [self.viewmodel.sendCommentRaccommand execute:textf.text];
    }];
    [self.view addSubview:self.sendView];
    self.viewmodel.sendmessageview = self.sendView;
    
    
    [[self.viewmodel.raccommand.executionSignals switchToLatest] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self freshUI];
    }];
    
    //获取数据
    [self.viewmodel.raccommand execute:@(1)];
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_Fresh_Userinfo object:nil];
//    });
}

- (void)freshUI{
    if (self.viewmodel.model != nil) {
        
        self.bottomView.hidden = NO;
        self.navigationItem.rightBarButtonItem.customView.hidden = NO;
        [self freshContrastCircle];
        
       
        if ([self.viewmodel.model.cardetailInfoModel.FAVORITE_FLAG isEqualToString:@"N"]) {
            self.isCollect = 2;
            [self.collectBtn setImage:IMG(@"ic_car_detail_farorite") forState:UIControlStateNormal];
        } else {
             self.isCollect = 1;
            [self.collectBtn setImage:IMG(@"collect_yellow") forState:UIControlStateNormal];
            
        }
        
    }else{
        
        self.navigationItem.rightBarButtonItem.customView.hidden = YES;
        [self.navigationController.navigationBar setCustomBgColor:Common_NavigroundColor];
    }
}

- (void)freshContrastCircle{
    self.circleview.hidden = ![CarDetailMainModel hasChooseContrastWithID:self.SERIES_ID];
}

- (void)updateVaule{
    [self.viewmodel.raccommand execute:@(1)];
}



- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
     self.navigationController.navigationBar.translucent = YES;
    CGFloat y = self.tableview.contentOffset.y;
    [self.navigationController.navigationBar setCustomBgColor:[Common_NavigroundColor colorWithAlphaComponent:(y - 40)/(IS_IPHONE_X ? 88 + 40: 64 + 40)]];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setCustomBgColor:Common_NavigroundColor];
}


#pragma mark -------------------事件
- (void)collectAction{
    
    
    if (self.isCollect == 2) {
        
        //添加收藏
        UserRes *user = [CommonMethod getUser];
        if (!user) {
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
            return;
        }
        NSDictionary *params = @{
                                 @"FKEY":[CommonMethod createMD5Key:@"TOKEN"],
                                 @"TOKEN":user.TOKEN,
                                 @"USERNAME":user.mobile,
                                 @"ZSCXID":self.SERIES_ID
                                 };
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showWithStatus:nil];
        });
        
        [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_45 params:params md5Paraname:nil success:^(id  _Nullable response) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            self.isCollect = 1;
             [self.collectBtn setImage:IMG(@"collect_yellow") forState:UIControlStateNormal];
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showInfoWithStatus:@"收藏成功"];
                //                [SVProgressHUD dismissWithDelay:10];
            });
            
        } fail:^(NSError * _Nonnull error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            });
            
        }];
        
    } else {
        //删除收藏
        UserRes *user = [CommonMethod getUser];
        if (!user) {
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
            return;
        }
        NSDictionary *params = @{
                                 @"FKEY":[CommonMethod createMD5Key:@"FAVORITE_ID"],
                                 @"TOKEN":user.TOKEN,
                                 @"USERNAME":user.mobile,
                                 @"FAVORITE_ID":self.viewmodel.model.cardetailInfoModel.FAVORITE_ID
                                 };
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showWithStatus:nil];
        });
        
        [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_44 params:params md5Paraname:nil success:^(id  _Nullable response) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            self.isCollect = 2;
            [self.collectBtn setImage:IMG(@"ic_car_detail_farorite") forState:UIControlStateNormal];
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showInfoWithStatus:@"取消成功"];
                //                [SVProgressHUD dismissWithDelay:10];
            });
            
        } fail:^(NSError * _Nonnull error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            });
            
        }];
        
    }
    
   
    
}
#pragma mark --------分享
- (void)shareAction{
    
}
#pragma mark --------i跳转对比
- (void)pushtoContrasAction{
    
    Car_ContrastCarViewController *push = [[Car_ContrastCarViewController alloc]init];
//    [self.navigationController pushViewController:push animated:YES];
    BaseNavViewController *naiv = [[BaseNavViewController alloc]initWithRootViewController:push];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:naiv animated:YES completion:nil];
    });
}
#pragma mark --------客服
- (void)action1{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",@"400-1060988"];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
#pragma mark --------计算器
- (void)action2{
    Car_ContrastCalculatorViewController *push = [[Car_ContrastCalculatorViewController alloc]init];
    push.carmodel = self.viewmodel.model.cardetailInfoModel;
    [self.navigationController pushViewController:push animated:YES];
}

#pragma mark --------加入对比
- (void)action3{
    BOOL isOK = [CarDetailMainModel addToArchiverWithMolde:self.viewmodel.model];
    if (isOK) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showInfoWithStatus:@"添加成功"];
        });
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Car_CarDetailViewControllerFreshContrast" object:nil];
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showInfoWithStatus:@"已添加"];
        });
    }
}

#pragma mark --------预定
- (void)action4{
    UserRes *user = [CommonMethod getUser];
    if (!user) {
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
        return;
    }
    HomeBookViewController *controller  = [[HomeBookViewController alloc] init];
    controller.resultDict = self.viewmodel.modelDict;
    [self.navigationController pushViewController:controller animated:YES];
}






#pragma mark ------------
- (void)vm_scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat y = scrollView.contentOffset.y;
    if (scrollView.contentInset.top == 0) {
        if (y > 40) {
            [self.navigationController.navigationBar setCustomBgColor:[Common_NavigroundColor colorWithAlphaComponent:(y - 40)/(IS_IPHONE_X ? 88 + 40: 64 + 40)]];
        }else{
            [self.navigationController.navigationBar setCustomBgColor:UIColor.clearColor];
        }
    }
}


/**
 初始化
 
 */
- (UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.backgroundColor = Common_BackgroundGrayColor;
        _tableview.dataSource = self.viewmodel;
        _tableview.delegate = self.viewmodel;
        _tableview.rowHeight = UITableViewAutomaticDimension;
        _tableview.estimatedRowHeight = 100;
//        _tableview.separatorColor = Common_SepeColor;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.tableFooterView = [UIView new];
        _tableview.showsVerticalScrollIndicator = NO;
        _tableview.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    }return _tableview;
}



@end
